/*
 * Copyright (c) 2015 DHC Corporation.
 */
package cn.com.dhc.danlu.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.CheckVersionDelegate.CheckVersionListener;
import cn.com.dhc.danlu.activity.myself.ForgetPwdActivity;
import cn.com.dhc.danlu.activity.terminal.TerminalProgressActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.ActivePhoneProcess;
import cn.com.dhc.danlu.util.ActivePhoneProcess.IOnCancelActive;
import cn.com.dhc.danlu.util.ActivityUtils;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.MD5;
import cn.com.dhc.danlu.util.PushEngine;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.EditTextLayout;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.hd.mall.web.webservices.entity.request.login.LoginRequest;
import cn.com.hd.mall.web.webservices.entity.response.login.LoginResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;
import static cn.com.dhc.danlu.util.CommonConst.WebservicesConst.LOGIN_RESPONSE_SUCCESS_2;
import static cn.com.dhc.danlu.util.CommonConst.WebservicesConst.LOGIN_RESPONSE_SUCCESS_3;
import static cn.com.dhc.danlu.util.CommonConst.WebservicesConst.LOGIN_RESPONSE_SUCCESS_4;
import static cn.com.dhc.danlu.util.CommonConst.WebservicesConst.LOGIN_RESPONSE_SUCCESS_5;

/**
 * 登录画面
 *
 * @author MuWei
 * @version 1.00 2015/02/03 新建
 */
public class LoginActivity extends BaseActivity implements CheckVersionListener {

    /**
     * 用户名输入框
     */
    private EditText edtLoginName;

    /**
     * 登录按钮
     */
    private Button btnLogin;

    /**
     * 当前版本号码
     */
    private TextView tv_version;
    /**
     * 注册
     */
    private TextView tv_register;
    /**
     * 忘记密码
     */
    private TextView tv_forget_pwd;

    private EditTextLayout etl_input;

    private String loginName;
    private String password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //        delegate.setContentView(R.layout.layout_login, R.layout_login.class);
        setContentView(R.layout.layout_login);

        initViews();
        setViews();

        PushEngine.newInstance().pausePush();
        agent.clearLoginUser();
    }

    private void initViews() {
        edtLoginName = (EditText) findViewById(R.id.edtLoginName);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        tv_version = (TextView) findViewById(R.id.tv_version);
        tv_register = (TextView) findViewById(R.id.tv_register);
        tv_forget_pwd = (TextView) findViewById(R.id.tv_forget_pwd);
        etl_input = (EditTextLayout) findViewById(R.id.etl_input);
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    /**
     * 画面初始化
     */
    private void setViews() {
        tv_version.setText(CommonUtils.getAppVersioName(this));
        // 获取本地存储的用户名
        String loginName = getPreferenceUtils().getLoginName();
        // 显示在用户名输入框中
        edtLoginName.setText(loginName);
        // 设置监听
        setListener();
        // 版本检查
        //        CheckVersionDelegate checkVersionDelegate = new CheckVersionDelegate(danluTaskProxy, this, this);
        CheckVersionDelegate checkVersionDelegate = new CheckVersionDelegate(this, this);
        // 获取版本
        checkVersionDelegate.getVersion();
    }


    /**
     * 设置监听
     */
    private void setListener() {
        btnLogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 登录检查
                checkLogin();
            }
        });
        etl_input.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // 右下角为完成或默认（默认是为了防止某些输入法没有完成按钮，比如QQ输入法）
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_NONE) {
                    // 登录检查
                    checkLogin();
                }
                return false;
            }
        });
        tv_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
        tv_forget_pwd.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 跳转到 找回密码界面
                Intent intent = new Intent(LoginActivity.this, ForgetPwdActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 登录检查
     */
    private void checkLogin() {
        // 获取用户名
        loginName = edtLoginName.getText().toString();
        // 获取密码
        password = etl_input.getInputText();

        // 用户名输入判断
        if (TextUtils.isEmpty(loginName)) {
            // 未输入用户名，弹出Toast提醒用户，返回
            ToastUtil.getInstance().show(R.string.input_login_name_label);
            return;
        }
        // 密码输入判断
        if (TextUtils.isEmpty(password)) {
            // 未输入密码，弹出Toast提醒用户，返回
            ToastUtil.getInstance().show(R.string.input_password_label);
            return;
        }
        // 用户名长度小于3位
        if (loginName.length() < 3) {
            ToastUtil.getInstance().show(R.string.login_write_error);
            return;
        }
        // 密码长度小于6
        if (password.length() < 6) {
            ToastUtil.getInstance().show(R.string.login_write_error);
            return;
        }
        // 用户名与密码均输入，进行登录操作，密码使用MD5加密
        login(loginName, MD5.getMD5Str(password));
    }

    /**
     * 登录
     *
     * @param loginName
     *         用户名
     * @param password
     *         MD5加密后的密码
     */
    private void login(final String loginName, final String password) {
        CommonUtils.hideSoftInputFromWindow(LoginActivity.this, edtLoginName);
        // request
        LoginRequest form = new LoginRequest();
        // 参数：用户名
        form.setUsername(loginName);
        // 参数：MD5加密后的密码
        form.setPassword(password);

        // 登录
        // 当前用户如果用的手机号码登陆-->该手机号码尚未激活...对话框提示
        // 当前用户如果使用的账号登陆 并且手机号码未激活
        agent.getApi()
                .login(form)
                .compose(OperatorUtils.<LoginResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<LoginResponse>(this, R.string.loging_ing) {
                    @Override
                    protected void onSuccess(LoginResponse model) {
                        String telStatus = model.getTelStatus();
                        if (TextUtils.isEmpty(telStatus) || telStatus.equals("1")) {
                            // 未激活
                            model.setTelStatus("1");
                        } else {
                            // 已经激活了
                            model.setTelStatus("0");
                        }
                        // 登录成功
                        // 将用户数据保存到Application中
                        agent.setLoginUser(model);

                        // 终端店版用以下代码
                        // 该用户为终端店用户
                        if (agent.isTerminalRole()) {
                            // 判断当前用户手机号是否需要激活
                            String isNeedActive = model.getTelStatus();
                            if (isNeedActive.equals("1")) {
                                // 未激活
                                showActiveDialog();
                            } else {
                                // 已经激活
                                handleNormalSucLogic(model);
                            }
                        } else {
                            // 弹出错误信息
                            createRoleErrorDialog(R.string.login_role_error_terminal_label);
                        }
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        if (code.equals(LOGIN_RESPONSE_SUCCESS_2)) {
                            return getResources().getString(R.string.login_error_no_user);
                        } else if (code.equals(LOGIN_RESPONSE_SUCCESS_4)) {
                            return getResources().getString(R.string.login_error_user_pwd_fail);
                        } else if (code.equals(LOGIN_RESPONSE_SUCCESS_3)) {
                            // 终端店正在审核中
                            // 跳转到审批进度界面
                            Intent intent = new Intent(LoginActivity.this, TerminalProgressActivity.class);
                            intent.putExtra("loginname", loginName);
                            intent.putExtra("password", password);
                            startActivity(intent);
                            finish();
                            return getResources().getString(R.string.store_checked);
                        } else if (code.equals(LOGIN_RESPONSE_SUCCESS_5)) {
                            return getResources().getString(R.string.login_error_user_add_fail);
                        } else {
                            return getResources().getString(R.string.unknow_exception);
                        }
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    /**
     * 弹出激活对话框
     */
    public void showActiveDialog() {
        ActivePhoneProcess process = new ActivePhoneProcess();
        process.setSwitchFragmentStatus(true);
        process.setOnCancelActiveListener(new IOnCancelActive() {
            @Override
            public void cancelActive() {
                handleNormalSucLogic(agent.getLoginUser());
            }

            @Override
            public void confirmActive() {
                handleSetAttrLogic(agent.getLoginUser());
                finish();
            }
        });
        process.showActiveDialog(this, true);
    }

    public void handleSetAttrLogic(LoginResponse loginResponse) {
        PushEngine.newInstance().resumePush();
        PushEngine.newInstance().setAlias(loginResponse.getUserId());
        PushEngine.newInstance().setTopic(CommonConst.TOPIC_PREFIX + agent.getLoginUser().getCompanyId());
        PushEngine.newInstance().setTopic(CommonConst.TAG_ENVELOP + agent.getLoginUser().getCompanyId());
        // 账号统计
        MobclickAgent.onProfileSignIn(loginResponse.getUserId());
        // 保存用户名与密码
        getPreferenceUtils().setLoginNameAndPassword(edtLoginName.getText().toString(), MD5.getMD5Str(etl_input.getInputText()));
        getPreferenceUtils().setUserId(loginResponse.getUserId());
        getPreferenceUtils().setFullName(loginResponse.getFullName());
    }

    /**
     * 登陆成功后的回调
     */
    public void handleNormalSucLogic(LoginResponse loginResponse) {
        handleSetAttrLogic(loginResponse);
        // 跳转到首页画面
        //        ActivityUtils.startMainMenuActivity(delegate.getContext());
        ActivityUtils.startMainMenuActivity(LoginActivity.this);
        // 本画面结束
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 弹出错误信息
     *
     * @param resId
     *         字符串资源Id
     */
    private void createRoleErrorDialog(int resId) {
        // 创建Builder
        //        ViewDialog.Builder builder = new ViewDialog.Builder(delegate.getContext());
        ViewDialog.Builder builder = new ViewDialog.Builder(LoginActivity.this);
        // 设置标题
        builder.setTitle(R.string.login_role_error_title);
        // 设置信息
        builder.setMessage(resId);
        // 设置Positive按钮点击监听
        builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 对话框关闭
                dialog.dismiss();
            }
        });

        // 设置不能通过返回键关闭对话框
        builder.setCancelable(false);
        // 创建对话框并显示
        builder.create().show();
    }

    @Override
    public void finishActivity() {
        this.finish();
    }
}